package net.stuffrepos.bricknetcenter.plugins.bricklink;

import java.util.List;
import net.stuffrepos.bricknetcenter.database.DataManager.InformationManager.InformationNode;
import net.stuffrepos.bricknetcenter.database.schema.Information;
import net.stuffrepos.bricknetcenter.http.HttpParser;
import net.stuffrepos.bricknetcenter.http.HttpResponse;
import net.stuffrepos.bricknetcenter.http.util.HtmlParser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class BrickLinkItemTypesRequest extends BrickLinkCatalogDownloadRequest {
    
    private static final Log log = LogFactory.getLog(BrickLinkItemTypesRequest.class);

    public BrickLinkItemTypesRequest() {
        super(ViewType.ItemTypes, "", "", "");
    }

    @Override
    public Class<? extends HttpParser> getParserClass() {
        return Parser.class;
    }
    
    @Override
    public Object[] getParserArguments() {
        return new Object[0];
    }

    private static InformationNode getItemTypesNode() throws Exception {
        return BrickLinkHttpProvider.getProviderNode().addChild(Information.Type.Group, "ItemTypes");
    }

    public static class Parser extends HtmlParser implements HttpParser {

        @Override
        public void parseDocument(HttpResponse response, Document document) throws Exception {
            for (Element item : (List<Element>) document.getRootElement().getChildren("ITEM", document.getRootElement().getNamespace())) {
                parseItem(item);
            }
        }

        private void parseItem(Element item) throws Exception {
            String id = item.getChildTextNormalize("ITEMTYPE", item.getNamespace()).trim();
            String name = item.getChildTextNormalize("ITEMTYPENAME", item.getNamespace()).trim();
            getItemTypesNode().addChild(
                    Information.Type.ItemType,
                    id).getChildren().addNode(Information.Type.Name, name);
        }
    }
}
